package com.gewu.teday.fragmnet

import android.Manifest.permission
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.Handler
import android.provider.MediaStore
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.SimpleAdapter
import android.widget.TextView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.gewu.teday.R
import com.gewu.teday.activity.MoenyActivity
import com.gewu.teday.utils.*
import kotlinx.android.synthetic.main.fouritem_layout.*
import kotlinx.android.synthetic.main.grid_view_item.view.*
import kotlinx.android.synthetic.main.idea_layout.view.*
import kotlinx.android.synthetic.main.mine_fragment.view.*
import kotlinx.android.synthetic.main.mine_laout.*
import kotlinx.android.synthetic.main.more_layout.view.*
import kotlinx.android.synthetic.main.toolbar_layout.*
import kotlinx.android.synthetic.main.toolbar_layout.view.*
import java.util.*
import kotlin.collections.ArrayList


class MineFragment : BaseFragment() {

    private val item = arrayOf(
        "订单管理",
        "优惠券",
        "地址管理",
        "任务",
        "大字模式",
        "客服中心",
        "钱包",
        "广告推广",
        "免流服务",
        "安全中心",
        "隐私设置",
        "头条公益"
    )
    private val icon = intArrayOf(R.mipmap.dingdan,
        R.mipmap.youhuiquan,
        R.mipmap.dizhi,
        R.mipmap.jihuarenwu,
        R.mipmap.dazi,
        R.mipmap.kefu,
        R.mipmap.qianbao,
        R.mipmap.guanggaokehusousuoci,
        R.mipmap.blob,
        R.mipmap.anquan,
        R.mipmap.yinsibaohu,
        R.mipmap.gongyi)


    private val permissions = arrayOf(permission.READ_EXTERNAL_STORAGE)
    private val CODE = 521

    override fun getLayoutId(): Int = R.layout.mine_fragment

    private var instance: SpUtils? = null

    override fun initView() {
        instance = SpUtils.instances;
        toolbar_main.visibility = View.VISIBLE
        toolbar_content.visibility = View.GONE
        tixian_list.visibility = View.GONE
    }

    override fun initData() {
        getPermission()
        view?.up_data?.setOnLongClickListener(object :View.OnLongClickListener{
            override fun onLongClick(p0: View?): Boolean {
                getPermission()
                if (instance?.decodeBoolean("ispermiss") == true) {
                    upData()
                }
                return true
            }
        })

        view?.im_action?.setOnClickListener {
            startActivity(Intent(context, MoenyActivity().javaClass))
        }

        hander?.postDelayed(Runnable {
            view?.let { setScrooll(it) }
        },1000)
    }

    private fun getPermission() {
        if (context?.let { ContextCompat.checkSelfPermission(it, permission.READ_EXTERNAL_STORAGE) } != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(permissions, 100)
        } else {
            setData()
        }
    }

    private fun setScrooll(view: View) {
        view.scroll.isHorizontalFadingEdgeEnabled = false
        val list = ArrayList<Map<String, Any>>()
        for (i in icon.indices) {
            val map: MutableMap<String, Any> = HashMap()
            map["image"] = icon[i]
            map["text"] = item[i]
            list.add(map)
        }
        val from = arrayOf("image", "text")
        val to = intArrayOf(R.id.image, R.id.text)
        view.grid_view.selector = ColorDrawable(Color.TRANSPARENT)
        val simpleAdapter = SimpleAdapter(context, list, R.layout.grid_view_item, from, to)
        view.grid_view.adapter = simpleAdapter
        view.grid_view.setExpanded(true)
    }


    var select_image: ImageView? = null

    /**
     * 修改数据
     */
    private fun upData() {
        val build = GwDialog(requireContext()).LayoutBuilder()
        val create = build.create(R.layout.updata_layout, false,Gravity.CENTER,R.drawable.shape)
        val view = build.getView()
        create.show()
        val nicheng = view?.findViewById<EditText>(R.id.nicheng)
        val toutiaoNum = view?.findViewById<EditText>(R.id.toutiaoNum)
        val huozanNum = view?.findViewById<EditText>(R.id.huozanNum)
        val fensiNum = view?.findViewById<EditText>(R.id.fensiNum)
        val guanzhuNum = view?.findViewById<EditText>(R.id.guanzhuNum)
        val xiaoxiNum = view?.findViewById<EditText>(R.id.xiaoxiNum)
        val rightNum = view?.findViewById<EditText>(R.id.rightNum)
        val cancel = view?.findViewById<ImageView>(R.id.cancel)
        select_image = view?.findViewById<ImageView>(R.id.select_image)
        val upOk = view?.findViewById<TextView>(R.id.upOk)
        val goImage = view?.findViewById<TextView>(R.id.goImage)

        nicheng!!.hint= if (instance!!.decodeString("nicheng") == "0") "请设置昵称" else instance!!.decodeString("nicheng")
        toutiaoNum!!.hint= if (instance!!.decodeString("toutiaoNum") == "0") "输入如：数据10万" else instance!!.decodeString("toutiaoNum")
        huozanNum!!.hint= if (instance!!.decodeString("huozanNum") == "0") "输入如：数据10万" else instance!!.decodeString("huozanNum")
        fensiNum!!.hint= if (instance!!.decodeString("fensiNum") == "0") "输入如：数据10万" else instance!!.decodeString("fensiNum")
        guanzhuNum!!.hint= if (instance!!.decodeString("guanzhuNum") == "0") "输入如：数据10万" else instance!!.decodeString("guanzhuNum")
        xiaoxiNum!!.hint= if (instance!!.decodeString("xiaoxiNum") == "0") "0" else instance!!.decodeString("xiaoxiNum")
        rightNum!!.hint= if (instance!!.decodeString("rightNum") == "0") "0" else instance!!.decodeString("rightNum")

        goImage?.setOnClickListener {
            val albumIntent = Intent(Intent.ACTION_PICK)
            albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
            startActivityForResult(albumIntent, CODE)
        }

        cancel?.setOnClickListener {
            realPathFromUri = null
            create.dismiss()
        }

        upOk?.setOnClickListener {

            if (nicheng.text.toString().isNotEmpty()) {
                instance?.encode("nicheng", nicheng.text.toString())
            }

            if (toutiaoNum.text.toString().isNotEmpty()) {
                instance?.encode("toutiaoNum", toutiaoNum.text.toString())
            }
            if (huozanNum.text.toString().isNotEmpty()) {
                instance?.encode("huozanNum", huozanNum.text.toString())
            }
            if (fensiNum.text.toString().isNotEmpty()) {
                instance?.encode("fensiNum", fensiNum.text.toString())
            }

            if (guanzhuNum.text.toString().isNotEmpty()) {
                instance?.encode("guanzhuNum", guanzhuNum.text.toString())
            }

            if (xiaoxiNum.text.toString().isNotEmpty()) {
                instance?.encode("xiaoxiNum", xiaoxiNum.text.toString())
            }

            if (rightNum.text.toString().isNotEmpty()) {
                instance?.encode("rightNum", rightNum.text.toString())
            }

            if (realPathFromUri?.isNotEmpty() == true) {
                realPathFromUri?.let { it1 -> instance?.encode("image", it1) }
            }

            setData()
            create.dismiss()
        }

    }

    /**
     * 设置UI数据
     */
    private fun setData() {
        instance?.encode("ispermiss", true)
        name?.text = instance?.decodeString("nicheng")
        toutiao_num?.text = instance?.decodeString("toutiaoNum")
        huozan_num?.text = instance?.decodeString("huozanNum")
        fensi_num?.text = instance?.decodeString("fensiNum")
        guanzhu_num?.text = instance?.decodeString("guanzhuNum")

        val toInt1 = instance?.decodeString("rightNum")?.toInt();
        nums_tool?.text = toInt1.toString()

        if (toInt1 != null) {
            when {
                toInt1 == 0 -> {
                    count_num_tool?.visibility = View.INVISIBLE
                }
                toInt1 > 99 -> {
                    count_num_tool?.visibility = View.VISIBLE
                    nums_tool?.text = "99+"
                }
                else -> {
                    count_num_tool?.visibility = View.VISIBLE
                    nums_tool?.text = toInt1.toString()
                }
            }
        }

        val toInt2 = instance?.decodeString("xiaoxiNum")?.toInt()
        nums?.text = toInt2.toString()
        if (toInt2 != null) {
            when {
                toInt2 == 0 -> {
                    count_num?.visibility = View.INVISIBLE
                }
                toInt2 >99 -> {
                    count_num?.visibility = View.VISIBLE
                    nums?.text="99+"
                }
                else -> {
                    count_num?.visibility = View.VISIBLE
                    nums?.text = toInt2.toString()
                }
            }
        }

        val toInt = toInt1!! + toInt2!!
        showNumss?.nums(toInt)

        val bitmap = Util.getBitmap(context, instance?.decodeString("image"))
        if (bitmap != null) {
            image.setImageBitmap(bitmap);
        }
    }

    private var showNumss:showNums? = null

    interface showNums{
        fun nums(num:Int)
    }

    fun setNums(showNums: showNums){
        this.showNumss = showNums
    }

    private var realPathFromUri: String? = null

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == CODE) {
            if (data != null) {
                image.post {
                    realPathFromUri = Util.getRealPathFromUri(context, data.data)
                    val bitmap = Util.getBitmap(context, realPathFromUri)
                    if (bitmap != null&&select_image!=null) {
                        select_image?.setImageBitmap(bitmap);
                    }
                }
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        if (requestCode == 100) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                setData()
            } else {
                if (activity?.let {
                        ActivityCompat.shouldShowRequestPermissionRationale(it,
                            permissions[0])
                    } != true) {
                    showDilog()?.show()
                }
            }
        } else {
            instance?.encode("ispermiss", false)
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    /**
     * 弹窗提示去设置权限
     */
    private fun showDilog(): GwDialog? {
        instance?.encode("ispermiss", false)
        val tipCreate = context?.let { GwDialog(it).TipBuilder() }
        return tipCreate?.setOnClick("去设置", "取消", object : GwDialog.OnClickListener {
            override fun onLeftClick(dialog: GwDialog) {
                JumpPermissionManagement.GoToSetting(activity)
                dialog.dismiss()
            }

            override fun onRightClick(dialog: GwDialog) {
                dialog.dismiss()
            }
        })?.create("请求权限", "请您授予权限否则头像将不能使用,请设置为仅在使用中允许。", false)
    }

}